package ${package.Stereotype}.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import ${package.Stereotype}.security.bean.LoginUser;
import ${package.Stereotype}.security.impl.CacheServiceImpl;
import ${package.Stereotype}.util.JwtUtil;
import ${package.Stereotype}.vo.ResultVo;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出登录成功 处理
 */
@Component
public class LogoutSuccess implements LogoutSuccessHandler {

    @Resource
    CacheServiceImpl cacheService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        ObjectMapper mapper = new ObjectMapper();
        ResultVo responseEntity = new ResultVo((Object) null);
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        responseEntity.setCode(200);
        responseEntity.setMsg("退出登录成功");
        responseEntity.setData(null);
        response.setStatus(200);
        String username = JwtUtil.getUsername(token);
        LoginUser userToken = new LoginUser();
        userToken.setUserName(username);
        cacheService.setLoginUser(userToken);
        response.getWriter().write(mapper.writeValueAsString(responseEntity));
    }
}
